package com.atguigu.service.impl;

import com.atguigu.config.RedissonConfig;
import com.atguigu.entity.BaseBrand;
import com.atguigu.exception.SleepUtils;
import com.atguigu.mapper.BaseBrandMapper;
import com.atguigu.service.BaseBrandService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 品牌表 服务实现类
 * </p>
 *
 * @author fumeng
 * @since 2021-10-29
 */
@Service
public class BaseBrandServiceImpl extends ServiceImpl<BaseBrandMapper, BaseBrand> implements BaseBrandService {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RedissonClient redissonClient;
    //分布式锁方案一
    @Override
    public void setNum() {
        //设置锁的值为UUID，
        String uuid = UUID.randomUUID().toString();
        //判断是否获得锁，利用redis的setnx命令。
        Boolean acquireLock  = redisTemplate.opsForValue().setIfAbsent("lock", uuid,3, TimeUnit.SECONDS);
        if (acquireLock){
            //拿到锁 如果doBusiness出现异常，锁会一直占用，无法释放
            doBusiness();
            /*//删除锁之前判断是否为自己的锁
            String redisUuid = (String)redisTemplate.opsForValue().get("lock");
            if (uuid.equals(redisUuid)){
                //业务完成后删除锁
                redisTemplate.delete("lock");
            }*/


            //定义一个脚本
            String luaScript="if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
            //把脚本封装到redisScript对象中
            redisScript.setScriptText(luaScript);
            //设置执行脚本之后返回上面类型
            redisScript.setResultType(Long.class);
            //准备执行脚本
            redisTemplate.execute(redisScript, Arrays.asList("lock"),uuid);


        }else{
            //设置睡眠时间
            SleepUtils.sleep1(50);
            //自旋
            setNum();
        }
    }

    private void doBusiness() {
        String  value = (String)redisTemplate.opsForValue().get("num");
        if (StringUtils.isEmpty(value)){
            redisTemplate.opsForValue().set("num","1");
        }else{
            Integer num = Integer.parseInt(value);
            redisTemplate.opsForValue().set("num",String.valueOf(++num));
        }
    }
}
